package com.lt.service.impl;

import com.lt.entity.File;
import com.lt.mapper.FileMapper;
import com.lt.service.COSFileService;
import com.lt.utils.TencentCOSUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;


/**
 * @Author :liteng
 * @Time : 2023-10-22 16:28
 */

@Service
public class COSFileServiceImpl implements COSFileService {

//    @Value("${tencent.SecretId}")
//    private String secretId;
//
//    @Value("${tencent.SecretKey}")
//    private String secretKey;
//
//    @Value("${tencent.region}")
//    private String region;

    @Value("${tencent.bucketName}")
    private String bucketName;

    @Value("${tencent.url}")
    private String path;

    private final COSClient cosClient;

    private final FileMapper fileMapper;

//    private final StudentMapper studentMapper;
//
//    private final TeacherMapper teacherMapper;

    public COSFileServiceImpl(COSClient cosClient, FileMapper fileMapper) {
        this.cosClient = cosClient;
        this.fileMapper = fileMapper;

    }

    /**
     * 上传文件，返回文件的下载地址或者null
     *
     * @param file
     * @return
     */
    @Override
    public String[] upload(MultipartFile file, Long num) {
        String url;
        File file1;
        String id;
        try {
            String originalFileName = file.getOriginalFilename();

            // 获得文件流
            InputStream inputStream = file.getInputStream();

            //设置文件key
            String filePath = TencentCOSUtils.getFileKey(originalFileName);


            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream, null);
//            COSClient cosClient1 = initCOSClient();
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 设置权限(公开读)

            cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            url = path + "/" + filePath;

            file1 = new File(0L, originalFileName, num, LocalDateTime.now(), url);
//            fileMapper.insertFiles(originalFileName, url, LocalDateTime.now(), num);
            fileMapper.insertFile(file1);
            id = String.valueOf(file1.getId());

        } catch (CosClientException clientException) {
            clientException.printStackTrace();
            return null;
//            url = null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
//            url = null;
//            throw new RuntimeException(e);
        }
        return new String[]{id, url};

    }
}
